/*
 * @(#)HttpClientContext.java $version 2011. 10. 14
 * 
 * Copyright 2011 NHN Corp. All rights Reserved.
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hangame.mbl.bo.http;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.hancore.util.http.HttpClientSimple;
import com.nhncorp.hancore.util.xml.XMLDataMap;
import com.nhncorp.hancore.util.xml.XMLMapper;

// TODO: Auto-generated Javadoc
/**
 * httpclient로 HTTP API 호출후 XMLDataMap에 매핑과정의 공통부분 template context로 만듬.
 * @author khpark
 */
public class HttpClientContext {
	
	/** The log. */
	private static Log log = LogFactory.getLog(HttpClientContext.class);

	/**
	 * Do get xml data map template.
	 * 
	 * @param strategy the strategy
	 * @return the xML data map
	 */
	public XMLDataMap doGetXmlDataMapTemplate(HttpClientStrategy strategy) {
		String responseXML = "";

		InputStream in = null;
		XMLMapper mapper = null;
		XMLDataMap map = null;

		int result = -1;

		HttpClientSimple client = strategy.makeHttpClient();

		try {
			result = client.execute();
		} catch (Exception e) {
			log.error(e, e);
			return null;
		}

		if (result == HttpStatus.SC_OK) { //정상적인 응답이 오면
			byte[] resRaw = client.getResponseBody();
			try {
				responseXML = new String(resRaw, "UTF8");
			} catch (Exception e1) {
				log.error(e1, e1);
				return null;
			}
			log.debug(responseXML);

		} else {
			log.error("게시판 목록 API HTTP 호출 에러. 응답코드 = " + result);
			return null;
		}

		try {
			in = new ByteArrayInputStream(responseXML.getBytes("UTF8"));
			mapper = new XMLMapper(in);
			map = mapper.getDataMap();
		} catch (Exception e) {
			log.error("xml을 map으로 바딩인 실패", e);
			return null;
		}

		return map;
	}
}
